const Dict = require('../models/dictModel');
const Response = require('../utils/response');

class DictController {
    // 创建字典
    async createDict(ctx) {
        try {
            const dict = await Dict.create(ctx.request.body);
            ctx.status = 201;
            ctx.body = dict;
        } catch (error) {
            ctx.status = 400;
            ctx.body = { message: error.message };
        }
    }

    // 获取所有字典
    async getDicts(ctx) {
        try {
            const { page = 1, limit = 10, name = '' } = ctx.query;
            const skip = (page - 1) * limit;

            // 构建查询条件
            const query = {};
            if (name) {
                query.name = { $regex: name, $options: 'i' };
            }

            // 获取总数
            const total = await Dict.countDocuments(query);

            // 获取分页数据
            const dicts = await Dict.find(query)
                .skip(skip)
                .limit(Number(limit))
                .sort({ createdAt: -1 });

            ctx.body = Response.success({
                total,
                page: Number(page),
                limit: Number(limit),
                data: dicts
            });
        } catch (error) {
            ctx.status = 500;
            ctx.body = Response.error(error.message);
        }
    }

    // 根据名称获取字典
    async getDictByName(ctx) {
        try {
            const dict = await Dict.findOne({ 
                name: ctx.params.name,
                status: true 
            });
            if (!dict) {
                ctx.status = 404;
                ctx.body = { message: '字典不存在' };
                return;
            }
            ctx.body = dict;
        } catch (error) {
            ctx.status = 500;
            ctx.body = { message: error.message };
        }
    }

    // 更新字典
    async updateDict(ctx) {
        try {
            const dict = await Dict.findOneAndUpdate(
                { id: ctx.params.id },
                ctx.request.body,
                { new: true, runValidators: true }
            );
            if (!dict) {
                ctx.status = 404;
                ctx.body = Response.error('字典不存在', 404);
                return;
            }
            ctx.body = Response.success(dict);
        } catch (error) {
            ctx.status = 400;
            ctx.body = Response.error(error.message);
        }
    }

    // 删除字典
    async deleteDict(ctx) {
        try {
            const dict = await Dict.findOneAndDelete({ id: ctx.params.id });
            if (!dict) {
                ctx.status = 404;
                ctx.body = Response.error('字典不存在', 404);
                return;
            }
            ctx.body = Response.success(null, '删除成功');
        } catch (error) {
            ctx.status = 500;
            ctx.body = Response.error(error.message);
        }
    }
}

module.exports = new DictController(); 